<template>
  <!--车辆维修保养申请单-->
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <!-- 基本信息 -->
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <!-- <a-col :span="8">
            <a-form-model-item v-if="false" label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
              <a-input placeholder="请输入标题" :disabled="formDisabled" v-model="model.bpmBizTitle"></a-input>
            </a-form-model-item>
          </a-col> -->
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="documentNo">
                  <a-input v-model="model.documentNo" placeholder="请输入单据编号" disabled ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlerId">
                  <select-user-by-dep
                    :multi="false"
                    v-model="model.handlerId"
                    disabled ></select-user-by-dep>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <a-input v-model="model.createTime" placeholder="请输入申请时间" disabled ></a-input>
                </a-form-model-item>
              </a-col>
              <!--          <a-col :span="8">-->
              <!--            <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyUser">-->
              <!--              <select-person-input-->
              <!--                placeholder="请选择申请人"-->
              <!--                :disabled="formDisabled"-->
              <!--                @back="backUserInfo"-->
              <!--                v-model="model.applyUser"/>-->
              <!--            </a-form-model-item>-->
              <!--          </a-col>-->
              <!--          <a-col :span="8">-->
              <!--            <a-form-model-item label="申请单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyUnit">-->
              <!--              <j-select-depart placeholder="请输入申请单位" :disabled="formDisabled" v-model="model.applyUnit"/>-->
              <!--            </a-form-model-item>-->
              <!--          </a-col>-->
              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyDept">
                  <j-select-depart placeholder="请选择申请部门" disabled v-model="model.applyDept"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="经营团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="managementTeam">
                  <select-team-input :disabled="formDisabled" v-model="model.managementTeam" :tdlx="3" placeholder="请选择经营团队"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="车牌号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="carId">
                  <!-- <a-input :disabled=formDisabled v-model="model.carId" placeholder="请输入车牌号"  ></a-input> -->
                  <select-car-num-input placeholder="请选择车牌号" v-model="model.carId" :disabled="formDisabled" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="修报类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="repairReportType">
                  <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.repairReportType" dictCode="repaire_status" placeholder="请选择修报类型" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="维修厂" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="repairShop">
                  <a-input :disabled="formDisabled" v-model="model.repairShop" placeholder="请输入维修厂" ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="当前里程数(km)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="carKilometers">
                  <a-input :disabled="formDisabled" v-model="model.carKilometers" placeholder="请输入当前里程数(km)" ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="保险到期时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="usingType">
                  <!-- <a-date-picker :disabled="formDisabled" valueFormat="YYYY-MM-DD" placeholder="请选择保险到期时间始" @change="handleChange" v-model="model.insuranceStartTime"  style="width: 48%" />
              <span class="fontDiy">至</span>
              <a-date-picker :disabled="formDisabled"
                  :disabled-date="disabledDate"
                  :default-picker-value="this.model.insuranceStartTime"
                  valueFormat="YYYY-MM-DD"
                  placeholder="请选择结束时间" v-model="model.insuranceEndTime"  style="width: 48%" /> -->
                  <a-date-picker
                    :disabled="formDisabled"
                    :disabled-date="disabledDate"
                    valueFormat="YYYY-MM-DD"
                    placeholder="请选择保险到期时间"
                    v-model="model.insuranceEndTime"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="维修情况说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="faultCause">
                  <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.faultCause" rows="4" placeholder="请输入维修情况说明"/>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="24">
            <a-form-model-item label="故障描述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="faultDescribe">
              <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.faultDescribe" rows="4" placeholder="请输入故障描述"/>
            </a-form-model-item>
          </a-col> -->
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="维修明细">
            <a-row :gutter="48">
              <erp-car-maintenance-details-list ref="detailslist" :disabled="formDisabled"></erp-car-maintenance-details-list>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="3" header="附件信息">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fileInfo">
                  <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.fileInfo" ></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.fileInfo)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
              <!-- <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
                <a-button @click="submitForm">提 交</a-button>
              </a-col> -->
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
      <view-file-modal ref="viewFileModal"></view-file-modal>
    </j-form-container>
    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <erp-car-maintenance-form-print v-if="formBpm" id="carhandleContent" class="print_style" :formData="model" :formDataHistory="formData"></erp-car-maintenance-form-print>
  </a-spin>
</template>

<script>

import { getAction, httpAction } from '@/api/manage'
import { mapGetters } from 'vuex';
import { viewFile } from '@/utils/util'
import moment from 'moment';
import ErpCarMaintenanceDetailsList from '../../maintenancedetails/ErpCarMaintenanceDetailsList';
import SelectCarNumInput from './SelectCarNumInput';
import ErpCarMaintenanceFormPrint from './ErpCarMaintenanceFormPrint' // 打印
import ViewFileModal from '@/views/scy/components/ViewFileModal'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import Print from '@/utils/print/printarea.js';
export default {
    name: 'ErpCarMaintenanceForm',
    components: {
      ErpCarMaintenanceDetailsList,
      SelectUserByDep,
      SelectCarNumInput,
      ViewFileModal,
      SelectTeamInput,
      CommonFlowList,
      ErpCarMaintenanceFormPrint
    },
    mixins: [viewFile],
    props: {
      // 流程表单data
      formData: {
        type: Object,
        default: () => {},
        required: false
      },
      // 表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    watch: {
      activeKey(key) {
        this.$forceUpdate()
      }
    },
    data () {
      return {
        activeKey: ['1', '2', '3'],
        model: {
         },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
          // bpmBizTitle:[
          //   { required: true, message: '请输入标题!' }
          // ],
          // applyUser: [
          //   { required: true, message: '请选择申请人!', trigger: 'change'},
          // ],
          // applyUnit: [
          //   { required: true, message: '请选择申请单位!', trigger: 'change'},
          // ],
          applyDept: [
            { required: true, message: '请选择申请部门!', trigger: 'change' }
          ],
          managementTeam: [
            { required: true, message: '请选择经营团队!', trigger: 'change' }
          ],
          carId: [
              { required: true, message: '请输入车牌号!', trigger: 'blur' }
          ],
          repairReportType: [
              { required: true, message: '请输入修报类型!', trigger: 'blur' }
          ],
          repairShop: [
              { required: true, message: '请输入维修厂!', trigger: 'blur' }
          ],
          faultCause: [
              { required: true, message: '请输入故障原因!', trigger: 'blur' }
          ],
          faultDescribe: [
              { required: true, message: '请输入故障描述!', trigger: 'blur' }
          ],
          carKilometers: [
            { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确公里数!' }
          ]
        },
        url: {
          add: '/api/erp/carmaintenance/erpCarMaintenance/add',
          edit: '/api/erp/carmaintenance/erpCarMaintenance/edit',
          queryById: '/api/erp/carmaintenance/erpCarMaintenance/queryById',
          generatedFormNumber: '/api/erp/base/generatedFormNumber'
        },
        formUrlMobile: '/pages/synergy/erpCarMaintenanceList'
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      ...mapGetters(['userInfo']),
      moment,
      // 生成单号，反写到编号和标题
      generatedFormNumber() {
        getAction(this.url.generatedFormNumber, { prefix: 'CLWX', subSystemCode: '04' }).then(res => {
          if (res.success) {
            // 单据编号
            this.$set(this.model, 'documentNo', res.result)
            // 标题 申请人-单据编号
            this.$set(this.model, 'bpmBizTitle', this.userInfo().empName + '-' + res.result)
          }
        })
      },
      handleChange(value) {
        if (this.model.insuranceEndTime) {
          if ((this.model.insuranceEndTime).diff((this.model.insuranceStartTime), 'days') < 0) {
            this.model.insuranceEndTime = this.model.insuranceStartTime
          }
        }
      },
      disabledDate(current) {
        return current < moment(this.model.insuranceStartTime).subtract('day')
      },
      getBillNo () {
        const that = this
        const handlerId = this.userInfo().empId
        getAction(this.url.gainBillNo, { handlerId }).then((res) => {
          if (res.success) {
            that.model.documentNo = res.result// 单据编号
          }
        })
      },
      add () {
        this.edit(this.modelDefault);
        // this.getBillNo(); //获取单据编号
        this.model.handlerId = this.userInfo().empId;// 申请人
        this.model.applyDept = this.userInfo().deptId
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
        this.generatedFormNumber() // 获取单据编号
      },
      edit (record) {
        this.$refs['form'].clearValidate();
        this.model = Object.assign({}, record);
        if (this.model.id) {
          this.$refs.detailslist.initDictConfig(this.model.id)
        } else {
          this.$refs.detailslist.dataSource = []
        }
        this.visible = true;
      },
      // 渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId };
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },
      submitForm (type) {
        const that = this;
        let details = this.$refs.detailslist.submitForm()
        if (type == 'draft') {
        // 代表保存草稿不做校验
        this.submit(type)
      } else if (type == 'submit') {
        // 触发表单验证
        if (!details.length > 0) {
          this.$message.warning('请添加维修明细信息！');
          this.$emit('unButtonDisable');
          return
        }
        this.$refs.form.validate(valid => {
          if (valid) {
            that.submit(type)
          } else {
            that.$emit('unButtonDisable')
          }
        })
      } else {
        console.log('传参数，保存：draft，提交：submit')
      }
      },

      submit (type) {
      const that = this;
      let details = this.$refs.detailslist.submitForm() || []
      that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
            method = 'put';
        }
        this.model.erpCarMaintenanceDetailsList = details
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            if (method == 'post') {
              that.model.id = res.result;
            }
            that.$emit('ok', type, that.model);
          } else {
            that.$message.warning(res.message);
            that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$emit('unButtonDisable', error);
        }).finally(() => {
          that.confirmLoading = false;
        })
    },

      // 点击打印
      onPrint () {
        let print = new Print({
          el: '#carhandleContent',
          popTitle: '车辆维修申请详情 · 禾美环保',
          endCallback() {

          }
        })
      }
    }
  }
</script>
<style>
.print_style{
  position: absolute;
  top: 0;
  z-index: -1111;
}
  @import "../../../../utils/print.css";
</style>
